﻿using System;
using System.Linq.Expressions;
using System.Reflection;

// ReSharper disable CheckNamespace
namespace System.Linq.Expressions
// ReSharper restore CheckNamespace
{
    public static class ExpressionExtensions
    {
        public static string GetNameFromExpression(this LambdaExpression property)
        {
            if (property.Body is MemberExpression)
                return GetNameFromMemberExpression(((MemberExpression)property.Body));

            if (property.Body is UnaryExpression)
                return GetNameFromMemberExpression(((UnaryExpression)property.Body).Operand as MemberExpression);

            throw new ArgumentException("Can't find a member expression", "property");
        }

        public static string GetNameFromMemberExpression(this MemberExpression expression)
        {
            if (expression == null)
                throw new ArgumentException("The specified expression does not reference a property.", "expression");

            var property = expression.Member as PropertyInfo;
            if (property == null)
                throw new ArgumentException("The specified expression does not reference a property.", "expression");

            return property.Name;
        }
    }
}